﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Net;
using Teamcenter.Schemas.Soa._2006_03.Exceptions;
using Teamcenter.Services.Strong.Core;
using Teamcenter.Services.Strong.Core._2006_03.Session;
using Teamcenter.Soa;
using Teamcenter.Soa.Client;
using Teamcenter.Soa.Client.Model;
using Teamcenter.Soa.Exceptions;
using Teamcenter.Services.Strong.Core._2006_03.DataManagement;
using Teamcenter.Services.Strong.Core._2007_01.DataManagement;
using Teamcenter.Services.Strong.Core._2008_06.DataManagement;
using Teamcenter.Services.Strong.Query;
using Teamcenter.Services.Strong.Query._2006_03.SavedQuery;
using ImanQuery = Teamcenter.Soa.Client.Model.Strong.ImanQuery;
using SavedQueriesResponse = Teamcenter.Services.Strong.Query._2007_09.SavedQuery.SavedQueriesResponse;
using QueryInput = Teamcenter.Services.Strong.Query._2008_06.SavedQuery.QueryInput;
using QueryResults = Teamcenter.Services.Strong.Query._2007_09.SavedQuery.QueryResults;
using WorkspaceObject = Teamcenter.Soa.Client.Model.Strong.WorkspaceObject;
using User = Teamcenter.Soa.Client.Model.Strong.User;
using log4net;
using Teamcenter.Services.Internal.Strong.Core._2011_06.ICT;
using PreferenceResponceNamespace = Teamcenter.Services.Strong.Core._2010_04.Session;
using PreferenceInputNS = Teamcenter.Services.Strong.Core._2007_01.Session;

namespace TC4T_WinForm
{
    public class LoggerHelper
    {
        static log4net.ILog LOGGER = null;
        static LoggerHelper()
        {
            if (LOGGER == null)
            {
                LOGGER = log4net.LogManager.GetLogger(typeof(LoggerHelper));
            }
        }
        public static void LogTCStackError(Teamcenter.Soa.Client.Model.ErrorStack errortask,
            Type type)
        {
            if (errortask != null && errortask.Messages != null && errortask.Messages.Length > 0)
            {
                LOGGER.Error("********************" + type.ToString() + "********************");
                foreach (string s in errortask.Messages)
                {
                    LOGGER.Error(s);
                }
                LOGGER.Error("********************END " + type.ToString() + " END********************");
            }
        }
    }
    public class TCHelper
    {
        static log4net.ILog LOGGER = null;
        static TCHelper()
        {
            if (LOGGER == null)
            {
                LOGGER = log4net.LogManager.GetLogger(typeof(TCHelper));
            }
        }

        public static void LogERROR(string message)
        {
            Form1.RichTextBox.Text += "\n" + message;
            Form1.RichTextBox.Refresh();
        }

        #region item相关 property相关
        public static ServiceData LoadObjects(string[] uids)
        {
            DataManagementService dmService = DataManagementService.getService(MyTCSession.MySessionConnection);
            try
            {
                return dmService.LoadObjects(uids);
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }
            return null;
        }


        public static CreateItemsResponse CreateItems(int noOfItems, string typeStr,string itemName,string description)
        {
            DataManagementService dmService = DataManagementService.getService(MyTCSession.MySessionConnection);
            try
            {
                ItemIdsAndInitialRevisionIds[] itemIds = GenerateItemIds(noOfItems, typeStr);

                //// Populate form type
                //GetItemCreationRelatedInfoResponse relatedResponse = dmService.GetItemCreationRelatedInfo(typeStr, null);
                //String[] formTypes = new String[0];
                //if (relatedResponse.ServiceData.sizeOfPartialErrors() > 0)
                //    throw new ServiceException("DataManagementService.getItemCretionRelatedInfo returned a partial error.");

                //formTypes = new String[relatedResponse.FormAttrs.Length];
                //for (int i = 0; i < relatedResponse.FormAttrs.Length; i++)
                //{
                //    FormAttributesInfo attrInfo = relatedResponse.FormAttrs[i];
                //    formTypes[i] = attrInfo.FormType;
                //}
                ////////

                ItemProperties[] itemProps = new ItemProperties[itemIds.Length];
                for (int i = 0; i < itemIds.Length; i++)
                {
                    //// Create form in cache for form property population
                    //ModelObject[] forms = CreateForms(itemIds[i].NewItemId, formTypes[0],
                    //                                  itemIds[i].NewRevId, formTypes[1],
                    //                                  null, false);

                    ItemProperties itemProperty = new ItemProperties();

                    itemProperty.ClientId = "clientId";
                    itemProperty.ItemId = itemIds[i].NewItemId;//序号
                    itemProperty.RevId = itemIds[i].NewRevId;
                    itemProperty.Name = itemName;//"xiaojin_name";
                    itemProperty.Type = typeStr;
                    itemProperty.Description = description;//"创建对象";
                    itemProperty.Uom = "";
                    itemProps[i] = itemProperty;

                    //// Retrieve one of form attribute value from Item master form.
                    //ServiceData serviceData = dmService.GetProperties(forms, new String[] { "project_id" });
                    //if (serviceData.sizeOfPartialErrors() > 0)
                    //    throw new ServiceException("DataManagementService.getProperties returned a partial error.");
                    //Property property = null;
                    //try
                    //{
                    //    property = forms[0].GetProperty("project_id");
                    //}
                    //catch (NotLoadedException /*ex*/) { }


                    //// Only if value is null, we set new value
                    //if (property == null || property.StringValue == null || property.StringValue.Length == 0)
                    //{
                    //    itemProperty.ExtendedAttributes = new ExtendedAttributes[1];
                    //    ExtendedAttributes theExtendedAttr = new ExtendedAttributes();
                    //    theExtendedAttr.Attributes = new Hashtable();
                    //    theExtendedAttr.ObjectType = formTypes[0];
                    //    theExtendedAttr.Attributes["project_id"] = "project_id";
                    //    itemProperty.ExtendedAttributes[0] = theExtendedAttr;
                    //}
                }


                // *****************************
                // Execute the service operation
                // *****************************
                CreateItemsResponse response = dmService.CreateItems(itemProps, null, "");
                // before control is returned the ChangedHandler will be called with
                // newly created Item and ItemRevisions



                // The AppXPartialErrorListener is logging the partial errors returned
                // In this simple example if any partial errors occur we will throw a
                // ServiceException
                if (response.ServiceData.sizeOfPartialErrors() > 0)
                    throw new ServiceException("DataManagementService.createItems returned a partial error.");

                return response;
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }
            return null;
        }

        protected static ItemIdsAndInitialRevisionIds[] GenerateItemIds(int numberOfIds, String type)
        {
            // Get the service stub
            DataManagementService dmService = DataManagementService.getService(MyTCSession.MySessionConnection);

            GenerateItemIdsAndInitialRevisionIdsProperties[] properties = new GenerateItemIdsAndInitialRevisionIdsProperties[1];
            GenerateItemIdsAndInitialRevisionIdsProperties property = new GenerateItemIdsAndInitialRevisionIdsProperties();

            property.Count = numberOfIds;
            property.ItemType = type;
            property.Item = null; // Not used
            properties[0] = property;

            // *****************************
            // Execute the service operation
            // *****************************
            GenerateItemIdsAndInitialRevisionIdsResponse response = dmService.GenerateItemIdsAndInitialRevisionIds(properties);



            // The AppXPartialErrorListener is logging the partial errors returned
            // In this simple example if any partial errors occur we will throw a
            // ServiceException
            if (response.ServiceData.sizeOfPartialErrors() > 0)
                throw new ServiceException("DataManagementService.generateItemIdsAndInitialRevisionIds returned a partial error.");

            // The return is a map of ItemIdsAndInitialRevisionIds keyed on the
            // 0-based index of requested IDs. Since we only asked for IDs for one
            // data type, the map key is '0'
            Int32 bIkey = 0;
            Hashtable allNewIds = response.OutputItemIdsAndInitialRevisionIds;
            ItemIdsAndInitialRevisionIds[] myNewIds = (ItemIdsAndInitialRevisionIds[])allNewIds[bIkey];

            return myNewIds;
        }

        public static Teamcenter.Soa.Client.Model.ServiceData GetPropertyValues(string[] itemids, string[] attrNames)
        {
            if (itemids != null && itemids.Length > 0 && attrNames != null && attrNames.Length > 0)
            {
                List<Teamcenter.Soa.Client.Model.ModelObject> _mos = new List<ModelObject>();
                foreach (string id in itemids)
                {
                    ModelObject mo = QueryItemByItemID(id);
                    if (mo != null)
                    {
                        _mos.Add(mo);
                    }
                }
                return GetPropertyValues(_mos.ToArray(), attrNames);
            }
            return null;
        }

        /// <summary>
        /// 用于跟PropertyInfo一起使用。
        /// </summary>
        /// <param name="sd"></param>
        /// <param name="index"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string[] GetPropertyValuesByServiceData(Teamcenter.Soa.Client.Model.ServiceData sd, int index,string propertyName)
        {
            if (sd != null && propertyName != null)
            {
                ModelObject mo = sd.GetPlainObject(index);
                return mo.GetPropertyDisplayableValues(propertyName);
            }
            return null;
        }

        /// <summary>
        /// 用于跟PropertyInfo一起使用。
        /// </summary>
        /// <param name="sd"></param>
        /// <param name="index"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string GetPropertyValueByServiceData(Teamcenter.Soa.Client.Model.ServiceData sd, int index, string propertyName)
        {
            if (sd != null && propertyName != null)
            {
                ModelObject mo = sd.GetPlainObject(index);
                return mo.GetPropertyDisplayableValue(propertyName);
            }
            return null;
        }

        public static Teamcenter.Soa.Client.Model.ServiceData GetPropertyValues(Teamcenter.Soa.Client.Model.ModelObject[] Objects, string[] Attributes)
        {
            DataManagementService dmService = DataManagementService.getService(MyTCSession.MySessionConnection);
            try
            {
                return dmService.GetProperties(Objects, Attributes);
            }
            catch (Exception e)
            {
                LOGGER.Error(e);
            }
            return null;
        }

        public static Teamcenter.Services.Strong.Core._2010_09.DataManagement.SetPropertyResponse SetPropertyValues(Teamcenter.Services.Strong.Core._2010_09.DataManagement.PropInfo[] Info, string[] Options)
        {
            DataManagementService dmService = DataManagementService.getService(MyTCSession.MySessionConnection);
            try
            {
                return dmService.SetProperties(Info, Options);
            }
            catch (Exception e)
            {
                LOGGER.Error(e);
            }
            return null;
        }

        public static Teamcenter.Services.Strong.Core._2010_09.DataManagement.SetPropertyResponse SetPropertyValue(string item_id, Dictionary<string, string[]> atts)
        {
            if (item_id != null && atts != null)
            {
                Dictionary<string,Dictionary<string,string[]>> dic = new Dictionary<string,Dictionary<string,string[]>>();
                dic.Add(item_id,atts);
                return SetPropertyValues(new string[] { item_id }, dic);
            }
            return null;
        }

        public static Teamcenter.Services.Strong.Core._2010_09.DataManagement.SetPropertyResponse SetPropertyValues(string[]item_id,Dictionary<string,Dictionary<string,string[]>> itemIdAttrbs)
        {
            try
            {
                if (item_id != null && item_id.Length > 0)
                {
                    List<Teamcenter.Services.Strong.Core._2010_09.DataManagement.PropInfo> Infos = new List<Teamcenter.Services.Strong.Core._2010_09.DataManagement.PropInfo>();
                    foreach (string id in item_id)
                    {
                        ModelObject mo = QueryItemByItemID(id);
                        Dictionary<string, string[]> attnameValues = itemIdAttrbs[id];
                        if (mo != null && attnameValues != null)
                        {
                            Teamcenter.Services.Strong.Core._2010_09.DataManagement.PropInfo info = new Teamcenter.Services.Strong.Core._2010_09.DataManagement.PropInfo();
                            info.Object = mo;
                            info.Timestamp = DateTime.Now;
                            List<Teamcenter.Services.Strong.Core._2010_09.DataManagement.NameValueStruct1> _structs = new List<Teamcenter.Services.Strong.Core._2010_09.DataManagement.NameValueStruct1>();
                            foreach(KeyValuePair<string,string[]> pair in attnameValues)
                            {
                                Teamcenter.Services.Strong.Core._2010_09.DataManagement.NameValueStruct1 _stru = new Teamcenter.Services.Strong.Core._2010_09.DataManagement.NameValueStruct1();
                                _stru.Name = pair.Key;
                                _stru.Values = pair.Value;
                                _structs.Add(_stru);
                            }
                            info.VecNameVal = _structs.ToArray();
                            Infos.Add(info);
                        }
                    }

                    List<string> Opts = new List<string>();
                    if (Infos.Count > 0)
                    {
                        foreach (Teamcenter.Services.Strong.Core._2010_09.DataManagement.PropInfo info in Infos)
                        {
                            Opts.Add("ENABLE_PSE_BULLETIN_BOARD");
                        }
                    }

                    if (Infos.Count > 0)
                    {
                        return SetPropertyValues(Infos.ToArray(), Opts.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }
            return null;
        }

        /**
         * Create ItemMasterForm and ItemRevisionMasterForm
         *
         * @param IMFormName      Name of ItemMasterForm
         * @param IMFormType      Type of ItemMasterForm
         * @param IRMFormName     Name of ItemRevisionMasterForm
         * @param IRMFormType     Type of ItemRevisionMasterForm
         * @param parent          The container object that two
         *                        newly-created forms will be added into.
         * @return ModelObject[]  Array of forms
         *
         * @throws ServiceException         If any partial errors are returned
         */
        public static ModelObject[] CreateForms(String IMFormName, String IMFormType,
                                    String IRMFormName, String IRMFormType,
                                    ModelObject parent, bool saveDB) //throws ServiceException
        {
            //Get the service stub
            DataManagementService dmService = DataManagementService.getService(MyTCSession.MySessionConnection);
            FormInfo[] inputs = new FormInfo[2];
            inputs[0] = new FormInfo();
            inputs[0].ClientId = "1";
            inputs[0].Description = "";
            inputs[0].Name = IMFormName;
            inputs[0].FormType = IMFormType;
            inputs[0].SaveDB = saveDB;
            inputs[0].ParentObject = parent;
            inputs[1] = new FormInfo();
            inputs[1].ClientId = "2";
            inputs[1].Description = "";
            inputs[1].Name = IRMFormName;
            inputs[1].FormType = IRMFormType;
            inputs[1].SaveDB = saveDB;
            inputs[1].ParentObject = parent;
            CreateOrUpdateFormsResponse response = dmService.CreateOrUpdateForms(inputs);
            if (response.ServiceData.sizeOfPartialErrors() > 0)
                throw new ServiceException("DataManagementService.createForms returned a partial error.");
            ModelObject[] forms = new ModelObject[inputs.Length];
            for (int i = 0; i < inputs.Length; ++i)
            {
                forms[i] = response.Outputs[i].Form;
            }
            return forms;
        }

        public static ModelObject QueryItemByItemID(string item_id)
        {
            try
            {
                return queryItems("Item ID", item_id)[0];
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }
            return null;
        }

        public static ModelObject[] queryItems(string queryName, string queryStr)
        {

            ImanQuery query = null;

            // Get the service stub
            SavedQueryService queryService = SavedQueryService.getService(MyTCSession.MySessionConnection);
            DataManagementService dmService = DataManagementService.getService(MyTCSession.MySessionConnection);

            try
            {

                // *****************************
                // Execute the service operation
                // *****************************
                GetSavedQueriesResponse savedQueries = queryService.GetSavedQueries();


                if (savedQueries.Queries.Length == 0)
                {
                    if(LOGGER.IsInfoEnabled)
                        LOGGER.Info("There are no saved queries in the system.");
                    return null;
                }

                // Find one called 'Item Name'
                for (int i = 0; i < savedQueries.Queries.Length; i++)
                {

                    if (savedQueries.Queries[i].Name.Equals(queryName))//"Item Name"))
                    {
                        query = savedQueries.Queries[i].Query;
                        break;
                    }
                }
            }
            catch (ServiceException e)
            {
                LOGGER.Error("GetSavedQueries service request failed.");
                LOGGER.Error(e.Message);
                return null;
            }

            if (query == null)
            {
                if (LOGGER.IsInfoEnabled)
                    LOGGER.Info("There is not an 'Item Name' query.");
                return null;
            }

            try
            {
                // Search for all Items, returning a maximum of 25 objects
                QueryInput[] savedQueryInput = new QueryInput[1];
                savedQueryInput[0] = new QueryInput();
                savedQueryInput[0].Query = query;
                savedQueryInput[0].MaxNumToReturn = 25;
                savedQueryInput[0].LimitList = new Teamcenter.Soa.Client.Model.ModelObject[0];
                savedQueryInput[0].Entries = new String[] { queryName };//"Item Name" };
                savedQueryInput[0].Values = new String[1];
                savedQueryInput[0].Values[0] = queryStr;//"*";

                //*****************************
                //Execute the service operation
                //*****************************
                SavedQueriesResponse savedQueryResult = queryService.ExecuteSavedQueries(savedQueryInput);
                QueryResults found = savedQueryResult.ArrayOfResults[0];


                //System.Console.Out.WriteLine("");
                //System.Console.Out.WriteLine("Found Items:");
                // Page through the results 10 at a time
                String[] uids = new String[found.ObjectUIDS.Length];
                for (int i = 0; i < found.ObjectUIDS.Length; i++)
                {
                    //int pageSize = (i + 10 < found.ObjectUIDS.Length) ? 10 : found.ObjectUIDS.Length - i;
                    uids[i] = found.ObjectUIDS[i];
                }
                ServiceData sd = dmService.LoadObjects(uids);
                ModelObject[] foundObjs = new ModelObject[sd.sizeOfPlainObjects()];
                for (int k = 0; k < sd.sizeOfPlainObjects(); k++)
                {
                    foundObjs[k] = sd.GetPlainObject(k);
                }

                return foundObjs;
            }
            catch (ServiceException e)
            {
                LOGGER.Error("ExecuteSavedQuery service request failed.");
                LOGGER.Error(e);
            }
            return null;
        }

        #endregion

        #region Item Type
        /// <summary>
        /// 返回所有零组件的名称,显示名称，以及父级对象名称(“Item”)
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public static ItemDisplayName GetItemHyrachy(string typeName)
        {
            DataManagementService dmService = DataManagementService.getService(MyTCSession.MySessionConnection);
            try
            {
                Teamcenter.Services.Strong.Core._2008_06.DataManagement.BOWithExclusionIn[] Input = new Teamcenter.Services.Strong.Core._2008_06.DataManagement.BOWithExclusionIn[1];
                Teamcenter.Services.Strong.Core._2008_06.DataManagement.BOWithExclusionIn bow = new Teamcenter.Services.Strong.Core._2008_06.DataManagement.BOWithExclusionIn();
                bow.BoTypeName = typeName;//"Item";
                string[] exclusives = { "EngChange", "Part", "Design", "PSSignal", "PSConnection", "Schedule"
                ,"ScheduleTask","Architecture","AllocationMap","CAEItem","CAEBCItem","CAEConnItem","CAELoadItem","MEOP",
                "MEProcess","MEWorkarea","MEContext","MEGenericBOP","SwDesignComp","PhysicalPart","ChangeItem","ParmDef"
                                      ,"ParmDefBCD","ParmDefBitDef","ParmDefBool","ParmDefDate","ParmDefDbl","ParmDefHex"
                                      ,"ParmDefInt","ParmDefSED","ParmDefStr","ParmGrpVal","CalParm","ParmGrpDef","ValidationAgent"
                                      ,"ValData","CondValAgent","CondValData","Drawing","SSP0Frequency","ValidationReq"
                                      ,"DesignReq","Mes0MESTXLibrary","Mes0MESTXFolder","Mes0MESTXElement","Mes0MEWITemplate"
                                      ,"Mes0MEWIObjTempl","TransltnOffice","DC_ExtEntAdmin","DC_Procedure","DCt_Item"
                                      ,"DC_ComposedDoc","DC_ReviewerDoc","DC_Publication","GraphicOption","DC_Topic"};
                bow.ExclusionBOTypeNames = exclusives;
                Input[0] = new Teamcenter.Services.Strong.Core._2008_06.DataManagement.BOWithExclusionIn();
                Input[0] = bow;

                Teamcenter.Services.Strong.Core._2010_04.DataManagement.DisplayableSubBusinessObjectsResponse response = dmService.FindDisplayableSubBusinessObjectsWithDisplayNames(Input);
                if (response.Output != null && response.Output.Length > 0)
                {
                    ItemDisplayName itemNames = new ItemDisplayName();
                    foreach (Teamcenter.Services.Strong.Core._2010_04.DataManagement.BusinessObjectHierarchy h in response.Output[0].DisplayableBOTypeNames)
                    {
                        //if (LOGGER.IsInfoEnabled)
                        //    LOGGER.Info("显示名称:" + h.BoDisplayName + " 对象名称:" + h.BoName);

                        itemNames.DisplayItems.Add(h.BoDisplayName);
                        itemNames.BOName.Add(h.BoName);
                        itemNames.ItemParentDic.Add(h.BoDisplayName, h.BoParents);
                    }
                    return itemNames;
                }
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }

            return null;
        }

        /// <summary>
        /// LOV,Property,
        /// </summary>
        /// <param name="TypeNames"></param>
        /// <returns></returns>
        public static Teamcenter.Schemas.Soa._2011_06.Metamodel.TypeSchema GetTypeDetails(string[] TypeNames)
        {
            try
            {
                SessionRestBindingStub srb = new Teamcenter.Services.Strong.Core.SessionRestBindingStub(MyTCSession.MySessionConnection);
                return srb.GetTypeDescriptions(TypeNames);
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }
            return null;
        }

        public static Dictionary<string, List<string>> GetTypePropertyPairByTypeNames(string[] TypeNames)
        {
            try
            {
                if (TypeNames != null && TypeNames.Length > 0)
                {
                    Teamcenter.Schemas.Soa._2011_06.Metamodel.TypeSchema typeschema
                        = GetTypeDetails(TypeNames);
                    if (typeschema != null && typeschema.Types != null && typeschema.Types.Length > 0)
                    {
                        Dictionary<string, List<string>> retDic = new Dictionary<string, List<string>>();
                        foreach (Teamcenter.Schemas.Soa._2011_06.Metamodel.ModelType
                            mt in typeschema.Types)
                        {
                            if (!retDic.ContainsKey(mt.ClassName))//Object name
                            {
                                string className = mt.ClassName;
                                List<string> properties = new List<string>();
                                foreach (Teamcenter.Schemas.Soa._2011_06.Metamodel.PropertyDescriptor pd
                                    in mt.PropertyDescriptors)
                                {
                                    properties.Add(pd.Name);
                                }
                                retDic.Add(className, properties);
                            }
                            else
                            {
                                System.Console.WriteLine("");
                            }
                        }
                        return retDic;
                    }
                }
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }
            return null;  
        }
        #endregion

        #region Preference

        public static PreferenceResponceNamespace.MultiPreferenceResponse2 GetPreferences(PreferenceInputNS.ScopedPreferenceNames[] PreferenceNames)
        {
            SessionRestBindingStub service = new Teamcenter.Services.Strong.Core.SessionRestBindingStub(MyTCSession.MySessionConnection);
            try
            {
                return service.GetPreferences2(PreferenceNames);
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }
            return null;
        }

        public static Teamcenter.Services.Strong.Core._2006_03.Session.PreferencesResponse SetPreferences(Teamcenter.Services.Strong.Core._2006_03.Session.PrefSetting[] Settings)
        {
            SessionRestBindingStub service = new Teamcenter.Services.Strong.Core.SessionRestBindingStub(MyTCSession.MySessionConnection);
            try
            {
                return service.SetPreferences(Settings);
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }
            return null;
        }
        #endregion 

        #region ICT
        public static Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.InvokeICTMethodResponse InvokeICTMethod(string ClassName, string MethodName, Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Arg[] Args)
        {
            Teamcenter.Services.Internal.Strong.Core.ICTRestBindingStub stub = new Teamcenter.Services.Internal.Strong.Core.ICTRestBindingStub(MyTCSession.MySessionConnection);
            try
            {
                return stub.InvokeICTMethod(ClassName,MethodName,Args);
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }
            return null;
        }

        public static Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.InvokeICTMethodResponse
            GetTextValue()
        {
            Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Arg arg = new Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Arg();
            arg.Val = "DefaultDateFormat";
            return InvokeICTMethod("ICCTTextService", "getTextValue", new Teamcenter.Services.Internal.Strong.Core._2011_06.ICT.Arg[] { arg });
        }

        public static InvokeICTMethodResponse GetChildrenInfo(string uid, string typeName,string TypeCPPName)
        {
            Arg[] args = new Arg[4];
            args[0] = new Arg();
            args[0].Val = typeName;

            args[1] = new Arg();
            args[1].Val = TypeCPPName;

            args[2] = new Arg();
            args[2].Val = uid;

            args[3] = new Arg();
            Structure s = new Structure();
            Arg sA = new Arg(); sA.Val = "false";
            s.Args = new Arg[] { sA };
            args[3].Structure = new Structure[]{s};

            return InvokeICTMethod("ICCT", "getChildrenInfo", args);
        }
        #endregion

        #region TC Session
        public static Teamcenter.Services.Strong.Core._2007_01.Session.GetTCSessionInfoResponse GetTCSessionInfo()
        {
            SessionRestBindingStub stub = new SessionRestBindingStub(MyTCSession.MySessionConnection);
            return stub.GetTCSessionInfo();
        }
        #endregion

        #region UID
        public static ServiceData GetServiceDataByUid(string[] Uids,string[] attrs)
        {
            if (Uids != null && Uids.Length > 0 && attrs!=null && attrs.Length>0)
            {
                ServiceData sd = TCHelper.LoadObjects(Uids);
                if (sd != null && sd.sizeOfPartialErrors() == 0)
                {
                    if (sd.sizeOfPlainObjects() > 0)
                    {
                        ModelObject[] mos = new ModelObject[sd.sizeOfPlainObjects()];
                        for (int i = 0; i < sd.sizeOfPlainObjects(); i++)
                        {
                            mos[i] = sd.GetPlainObject(i);
                        }
                        ServiceData s1 = TCHelper.GetPropertyValues(
                            mos,attrs);
                        return s1;
                    }
                }
            }
            return null;
        }


        /// <summary>
        /// <Uid><Attr<properties>>
        /// </summary>
        /// <param name="Uids"></param>
        /// <param name="attrs"></param>
        /// <returns></returns>
        public static Dictionary<string,Dictionary<string,Property>> GetPropertiesByUids(string[] Uids, string[] attrs)
        {
            ServiceData sd = GetServiceDataByUid(Uids, attrs);
            if (sd == null)
                return null;
            int sizeofpain = sd.sizeOfPlainObjects();
            if (sizeofpain == 0)
                return null;
            try
            {
                Dictionary<string, Dictionary<string, Property>> retDic = new Dictionary<string, Dictionary<string, Property>>();
                for (int i = 0; i < sizeofpain; i++)
                {
                    ModelObject mo = sd.GetPlainObject(i);
                    Dictionary<string, Property> _dic = new Dictionary<string, Property>();
                    foreach (string att in attrs)
                    {
                        if (_dic.ContainsKey(att))
                            _dic[att] = mo.GetProperty(att);
                        else
                            _dic.Add(att, mo.GetProperty(att));
                    }
                    if (retDic.ContainsKey(mo.Uid))
                        retDic[mo.Uid] = _dic;
                    else
                        retDic.Add(mo.Uid, _dic);
                }
                return retDic;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }

    public class MyTCSession
    {
        static readonly string conStr = "http://TC4T:7001/tcweb";
        static Teamcenter.ClientX.Session _innerSession = null;
        static object _lockObject = new object();
        static User _user = null;
        static ILog LOGGER = LogManager.GetLogger(typeof(MyTCSession));
        public static User LoginUser
        {
            get
            {
                return _user;
            }
        }
        public static Connection MySessionConnection
        {
            get
            {
                if (_innerSession==null || _innerSession.getConnection() == null)
                {
                    InitSession();
                }
                return _innerSession.getConnection();
            }
        }
        public static Teamcenter.ClientX.Session MySession
        {
            get
            {
                return _innerSession;
            }
        }
        public static void InitSession()
        {
            if (_innerSession == null)
            {
                lock (_lockObject)
                {
                    if (_innerSession == null)
                    {
                        if (!string.IsNullOrEmpty(conStr))
                        {
                            try
                            {
                                _innerSession = new Teamcenter.ClientX.Session(conStr);
                            }
                            catch (Exception ex)
                            {
                                LOGGER.Error(ex);
                                throw ex;
                            }
                        }
                    }
                }
            }
        }

        public static User Login(string name, string password, string group,
            string role, string discriminator)
        {
            try
            {
                if (_user == null)
                {
                    _user = _innerSession.login(name,password,group,role,discriminator);
                    return _user;
                }
                else
                    return _user;
            }
            catch (Exception ex)
            {
                LOGGER.Error(ex);
            }
            return null;
        }
        public static void LogOut()
        {
            if (_innerSession != null)
                _innerSession.logout();
        }
    }

    public class ItemDisplayName
    {
        List<string> _DisplayItems = new List<string>();
        List<string> _BoName = new List<string>();
        Dictionary<string, string[]> _parent = new Dictionary<string, string[]>();

        public Dictionary<string, string[]> ItemParentDic
        {
            get { return _parent; }
        }
        public List<string> DisplayItems
        {
            get
            {
                return _DisplayItems;
            }
        }

        public List<string> BOName
        {
            get { return _BoName; }
        }
    }
}
